<template>
  <div class='container'>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="card">
          <div slot="header" class="clearfix">
            <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
          </div>
          <div class="card-body">
            <el-tree
              ref="tree" :props="props" :data="data" :highlight-current="false" node-key="id"
              :default-expand-all="true" :filter-node-method="filterNode2" :render-content="renderContent"
            ></el-tree>
          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="sticky-card">
          <div slot="header" class="clearfix">
            设置权限
          </div>
          <div class="card-body">
            <el-form class="form" ref="formEdit" :model="formEdit"
              label-width="120px" :rules="rules"
            >
              <el-form-item label="用户名称" prop="userName">
                <el-input disabled v-model="formEdit.userName"></el-input>
              </el-form-item>
              <el-form-item label="用户工号" prop="userCode">
                <el-input disabled v-model="formEdit.userCode"></el-input>
              </el-form-item>
              <el-form-item label="栏目权限" prop="classChoose">
                <el-popover
                  placement="bottom-start"
                  trigger="click"
                  @show="showTree"
                  v-model="visiblePopover2"
                >
                  <el-input
                    placeholder="输入关键字进行过滤"
                    v-model="filterText6">
                  </el-input>
                  <el-tree
                    :filter-node-method="filterNode" show-checkbox @check-change="checkEditChange"
                    ref="tree6" :props="propsClass" :data="treeList" :highlight-current="false" node-key="id"
                    :default-expanded-keys="[0]"
                  >
                  </el-tree>
                  <el-select
                    :clearable="true" multiple
                    popper-class="hide" slot="reference" v-model="formEdit.classChoose" type="text"
                    placeholder="请输入"
                  >
                    <el-option
                      v-for="(item, index) in options" v-show="false" :key="index" :value="item.id" :label="item.name"
                    ></el-option>
                  </el-select>
                </el-popover>
              </el-form-item>
              <div style="text-align: center">
                <el-button :disabled="!formEdit.userCode" @click="handleCancel">取消修改</el-button>
                <el-button :disabled="!formEdit.userCode" type="primary" @click="updateData">确认修改</el-button>
              </div>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog :close-on-click-modal="false" title="新增" :visible.sync="centerDialogVisible" width="60%" center>
      <el-form class="form" ref="formCreate" :model="formCreate"
        label-width="120px" :rules="rules"
      >
        <el-form-item label="用户工号" prop="userCode">
          <el-input @change="getUserName" v-model="formCreate.userCode"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input disabled v-model="formCreate.userName"></el-input>
        </el-form-item>
        <el-form-item label="栏目权限" prop="classChoose">
          <el-popover
            placement="bottom-start"
            trigger="click"
            @show="filterText5 = ''"
            v-model="visiblePopover"
          >
            <el-input
              placeholder="输入关键字进行过滤"
              v-model="filterText5">
            </el-input>
            <el-tree
              :filter-node-method="filterNode" show-checkbox @check-change="checkCreateChange"
              ref="tree5" :props="propsClass" :data="treeList" :highlight-current="false" node-key="id"
              :default-expanded-keys="[0]"
            >
            </el-tree>
            <el-select
              :clearable="true" multiple
              popper-class="hide" slot="reference" v-model="formCreate.classChoose" type="text"
              placeholder="请输入"
            >
              <el-option
                v-for="(item, index) in options" v-show="false" :key="index" :value="item.id" :label="item.name"
              ></el-option>
            </el-select>
          </el-popover>
        </el-form-item>
        <div style="text-align: center">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="createData">确认</el-button>
        </div>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
  import {
    userList,
    getUserName,
    addUserClass,
    getUserClass,
    updateUserClass,
    deleteUserClass
  } from '../../api/systemManagement'
  import { classList } from '../../api/article'
  import pinyin from 'pinyin'

  export default {
    name: 'columnList',
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      },
      filterText5(val) {
        this.$refs.tree5.filter(val)
      },
      filterText6(val) {
        this.$refs.tree6.filter(val)
      }
    },
    created() {
      this.getList()
      this.getClass()
    },
    methods: {
      getList() {
        userList({}).then(response => {
          this.data[0].children = response.Data
        })
      },
      getClass() {
        const params = {
          pageNum: 1,
          pageSize: 99999
        }
        classList(params).then(response => {
          const temp = {}
          const result = []
          const data = response.Data
          const length = data.length
          for (let i = 0; i < length; i++) {
            temp[data[i].id] = data[i]
            this['options'].push(data[i])
          }
          for (let i = 0; i < length; i++) {
            if (temp[data[i].id].parentId && temp[data[i].parentId]) {
              if (!temp[data[i].parentId].children) {
                temp[data[i].parentId].children = []
              }
              temp[data[i].parentId].children.push(temp[data[i].id])
            } else {
              result.push(temp[data[i].id])
            }
          }
          this['treeList'][0].children = result
        })
      },
      filterNode2(value, data) {
        if (!value) return true
        return data.userName.indexOf(value) !== -1 || pinyin(data.userName, {
          style: pinyin.STYLE_FIRST_LETTER,
          heteronym: true
        }).join('').indexOf(value) !== -1
      },
      filterNode(value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1 || pinyin(data.name, {
          style: pinyin.STYLE_FIRST_LETTER,
          heteronym: true
        }).join('').indexOf(value) !== -1
      },
      getUserName(val) {
        if (val) {
          getUserName({ userCode: val }).then(response => {
            this.formCreate.userName = response.Data[0].userName
            this.$message({
              type: 'success',
              message: '查询用户名称成功'
            })
          })
        }
      },
      checkCreateChange() {
        // this.formCreate.classChoose = this.$refs.tree5.getCheckedNodes().map(e => e.id)
        this.formCreate.classChoose = this.$refs.tree5.getCheckedNodes().filter(e => !e.children).map(e => e.id)
      },
      checkEditChange() {
        // this.formEdit.classChoose = this.$refs.tree6.getCheckedNodes().map(e => e.id)
        this.formEdit.classChoose = this.$refs.tree6.getCheckedNodes().filter(e => !e.children).map(e => e.id)
      },
      showTree() {
        this.filterText6 = ''
        this.$refs.tree6.setCheckedKeys(this.formEdit.classChoose)
      },
      resetForm() {
        this.formCreate = {
          userName: '',
          userCode: '',
          classChoose: [],
        }
        this.formEdit = {
          userName: '',
          userCode: '',
          classChoose: []
        }
        this.$nextTick(() => {
          if (this.$refs['tree5']) this.$refs.tree5.setCheckedKeys([])
          if (this.$refs['formCreate']) this.$refs['formCreate'].resetFields()
          if (this.$refs['formEdit']) this.$refs['formEdit'].resetFields()
        })
      },
      handleCreate(node, data, e) {
        e.stopPropagation()
        this.resetForm()
        this.centerDialogVisible = true
      },
      createData() {
        this.$refs['formCreate'].validate((valid) => {
          if (valid) {
            const params = {
              cmsClassIds: this.formCreate.classChoose,
              userCode: this.formCreate.userCode,
              userName: this.formCreate.userName
            }
            addUserClass(params).then(response => {
              this.centerDialogVisible = false
              this.$notify({
                title: '成功',
                message: '添加用户权限成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleCancel() {
        this.resetForm()
        this.centerDialogVisible = false
      },
      handleNodeClick(node, data, e) {
        this.$refs['formEdit'].resetFields()
        e.stopPropagation()
        getUserClass({ userCode: data.userCode }).then((response) => {
          const getData = response.Data[0]
          this.formEdit.userCode = getData.userCode
          this.formEdit.userName = getData.userName
          this.formEdit.classChoose = getData.userClassInfos.map(e => e.id)
        })
      },
      updateData() {
        this.$refs['formEdit'].validate((valid) => {
          if (valid) {
            const params = {
              cmsClassIds: this.formEdit.classChoose,
              userCode: this.formEdit.userCode,
              userName: this.formEdit.userName
            }
            updateUserClass(params).then(response => {
              this.$notify({
                title: '成功',
                message: '修改用户权限成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      remove(node, data, e) {
        e.stopPropagation()
        this.$confirm('确认删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUserClass({ userCode: data.userCode }).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      renderContent(h, { node, data, store }) {
        return (
          <span class={(node.isLeaf && node.level > 1) ? 'custom-tree-node' : 'custom-tree-node custom-tree-notLeaf'}>
            <span>
              <el-tooltip className='item' effect='dark'
                content={node.level > 1 ? node.label + '(' + node.data.userCode + ')' : node.label}
                placement='top-start'>
                <span
                  class='tree-label'>{node.level > 1 ? node.label + '(' + node.data.userCode + ')' : node.label}&nbsp;</span>
              </el-tooltip>
            </span>
            <span>
              {node.level == 1
                ? <el-button size='mini' type='text' on-click={(e) => this.handleCreate(node, data, e)}>新增用户</el-button>
                : ''}
              {node.level > 1
                ? <el-button
                  size='mini' type='text'
                  on-click={(e) => this.remove(node, data, e)}
                >删除</el-button>
                : ''}
              {node.level > 1
                ? <el-button
                  size='mini' type='text'
                  on-click={(e) => this.handleNodeClick(node, data, e)}
                >修改权限</el-button>
                : ''}
            </span>
          </span>)
      },
    },

    data() {
      return {
        filterText: '',
        filterText5: '',
        filterText6: '',
        centerDialogVisible: false,
        visiblePopover: false,
        visiblePopover2: false,
        treeList: [{
          name: '栏目列表',
          id: 0,
          children: []
        }],
        options: [],
        props: {
          label: 'userName',
          id: 'userCode'
        },
        propsClass: {
          label: 'name'
        },
        data: [{
          userName: '用户列表',
          userCode: 0,
          children: []
        }],
        rules: {
          userCode: [{ required: true, message: '请输入...', trigger: 'change' }],
          userName: [{ required: true, message: '请输入...', trigger: 'change' }],
          classChoose: [{ required: true, message: '请输入...', trigger: 'change' }]
        },
        formEdit: {
          userName: '',
          userCode: '',
          classChoose: []
        },
        formCreate: {
          userName: '',
          userCode: '',
          classChoose: []
        },
      }
    }
  }
</script>

<style type="scss" scoped>
  .col {
    width: inherit;
  }

  .card-body {
    margin-top: 1rem;
  }

  .form {
    max-width: 500px !important;
    margin: auto !important;
  }
</style>

<style>
  .el-tag {
    margin-right: 3px;
    background-color: rgba(64, 158, 255, .1);
    color: #409EFF;
    border-radius: 4px;
    padding: 0 3px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: 1px solid rgba(64, 158, 255, .2);
  }

  .el-tag--warning {
    background-color: rgba(230, 162, 60, .1);
    border-color: rgba(230, 162, 60, .2);
    color: #e6a23c;
  }

  .tree-label {
    display: inline-block;
    max-width: 145px;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .el-dialog__header {
    padding: 15px !important;
  }
</style>


